using System;
using System.ServiceProcess;
using System.Timers;
using Microsoft.Health.Samples.PatientConnect.TreyResearch.HealthVaultAdapter;

namespace Microsoft.Health.Samples.PatientConnect.TreyResearch.TreyResearchScheduler
{
    public partial class TreyResearchService : ServiceBase
    {
        private Timer _timer;

        public TreyResearchService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Service's OnStart event
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            long timerValue = 0;
            timerValue = ServiceInboundCalls.CalculateTimerValue();
            _timer = new Timer(timerValue);
            _timer.Elapsed += TimerElapsed;

            _timer.AutoReset = false;
            _timer.Enabled = true;
            _timer.Start();
        }

        /// <summary>
        /// Timer elapsed event of the scheduler.
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">ElapsedEventArgs</param>
        protected void TimerElapsed(object sender, ElapsedEventArgs e)
        {

            try
            {
                Logger.LogEvent("Scheduler started at:" + DateTime.Now.ToString(),SchedulerStatus.Started);
                ServiceInboundCalls.CallInboundMethods();
            }
            catch (Exception ex)
            {
                Logger.LogEvent(ex.Message, SchedulerStatus.Error);
            }

            try
            {
                ServiceOutboundCalls.CallOutboundMethods();
                Logger.LogSchedulersLastRun();
            }
            catch (Exception ex)
            {
                Logger.LogEvent(ex.Message, SchedulerStatus.Error);
            }

            _timer.Start();
        }
    }
}
